/*
 * Project Name spring-boot-tools
 * File Name ValidatorUtils
 * Package Name com.huxiaosu.tools.common.validator
 * Create Time 2024/7/16
 * Create by name：liujie
 */
package com.huxiaosu.tools.common.validator;

import com.huxiaosu.tools.common.exception.PlatformException;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;

import java.util.Set;

/**
 * Description
 *
 * @author liujie
 * @date 2024/7/16 10:39
 */
public class ValidatorUtils {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     * @param object 待校验对象
     * @throws PlatformException 校验不通过，则报BusinessException异常
     */
    public static void validateEntity(Object object, Class<?>... groups) throws PlatformException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            ConstraintViolation<Object> constraint = constraintViolations.iterator().next();
            throw new PlatformException(constraint.getMessage());
        }
    }
}